<?php
namespace command\factory;

class Service
{
    //服务配置
    private $config = [];

    /**
     * 构造函数，初始化配置
     *
     * @param array $config
     */
    public function __construct($config=[])
    {
        $this->config = array_merge($this->config,$config);
    }

    /**
     * 初始化模型类
     *
     * @param array $config
     * @return object
     */
    public static function init(array $config)
    {
        $class = new static($config);

        return $class;
    }
    
    /**
     * 创建服务
     *
     * @return void
     */
    public function create()
    {
     
        $path = app()->getBasePath()."service";

        if (!is_dir($path)) {
            mkdir($path, 0755, true);
        }

        $stub = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'service/stubs' . DIRECTORY_SEPARATOR . 'service.stub');

       
        foreach ($this->parseConfig() as $config) {

            $namespace = $config['namespace'];

            $pathName = $path . DIRECTORY_SEPARATOR . $config['service_name'] .".php";

            if(is_file($pathName))continue;//文件已存在跳过

            $method = $this->buildMethod($config['methods']);

            file_put_contents(
                $pathName,
                str_replace(
                    ['{$namespace}','{$use}','{$comment}','{$serviceName}','{$serviceMethod}'],
                    [$namespace,implode(PHP_EOL,$config['use']),$config['comment'],$config['service_name'],$method],
                    $stub
                )
            );

            return true;

        }
    }

    /**
     * 解析配置
     *
     * @return array
     */
    private function parseConfig()
    {
        return $this->config;
    }

    /**
     * 构建逻辑处理方法
     *
     * @param array $serviceMethod
     * @return void
     */
    private function buildMethod($serviceMethod)
    {
        $functions = [];
        foreach ($serviceMethod as $name=>$config) {
            $tplFile = __DIR__ . DIRECTORY_SEPARATOR . 'service/stubs' . DIRECTORY_SEPARATOR . 'method' . DIRECTORY_SEPARATOR . $config['type'] . '.stub';
            if(is_file($tplFile)){
                $tplstr = file_get_contents($tplFile);
                $functions[]=str_replace(
                    ['{$comment}','{$methodName}','{$model}','{$pk}','{$allowField}','{$with}','{$order}','{$wconfig}'],
                    [$config['comment'],$name,$config['model'],$config['pk'],$this->parseAllowField($config['allow_field']['field']??'[]'),$config['with']??'""',$config['order']??'""',$this->parseWconfig($config['query']['wconfig']??'[]')],
                    $tplstr
                );
            }
            
        }

        return implode(PHP_EOL.PHP_EOL,$functions);

    }
    
    /**
     * 构建可编辑字段
     *
     * @param mixed $allowField
     * @return void
     */
    private function parseAllowField($allowField)
    {
        if(!is_array($allowField))return $allowField;

        $allowStr ='[';

        foreach ($allowField as $field) {
            $allowStr .= '"'.$field.'",';
        }

        return trim($allowStr,',').']';
    }

    /**
     * 构建可查询条件
     *
     * @param mixed $wconfig
     * @return void
     */
    private function parseWconfig($wconfig)
    {
        if(!is_array($wconfig))return $wconfig;

        $configStr ='['.PHP_EOL."\t\t";

        foreach ($wconfig as $field=>$where) {
            $configStr .= "\t".'"'.$field.'"=>["'.$where[0].'","'.($where[1]??'=').'"],'.PHP_EOL."\t\t";
        }

        return trim($configStr,',').']';
    }
}